import os
import json
from flask import Flask, jsonify, render_template, request
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
import glob

app = Flask(__name__)

class FileChangeHandler(FileSystemEventHandler):
    def on_modified(self, event):
        if event.is_directory:
            return
        if event.src_path.endswith(('.json', '.jsonl')):
            print(f"File {event.src_path} has been modified")

def get_data_files():
    data_dir = os.path.join(os.path.dirname(__file__), 'datas')
    if not os.path.exists(data_dir):
        os.makedirs(data_dir)
    files = glob.glob(os.path.join(data_dir, '*.json*'))
    return [os.path.basename(f) for f in files]

def read_data(filename, start_idx=0, count=10):
    filepath = os.path.join('datas', filename)
    data = []
    
    if not os.path.exists(filepath):
        return []
        
    if filename.endswith('.jsonl'):
        with open(filepath, 'r', encoding='utf-8') as f:
            for idx, line in enumerate(f):
                if idx >= start_idx:
                    if len(data) >= count:
                        break
                    try:
                        data.append(json.loads(line.strip()))
                    except json.JSONDecodeError:
                        continue
    else:  # .json file
        try:
            with open(filepath, 'r', encoding='utf-8') as f:
                full_data = json.load(f)
                if isinstance(full_data, list):
                    data = full_data[start_idx:start_idx + count]
                else:
                    data = [full_data]
        except json.JSONDecodeError:
            return []
            
    return data

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/files')
def get_files():
    return jsonify(get_data_files())

@app.route('/data')
def get_json_data():
    filename = request.args.get('file', '')
    start_idx = int(request.args.get('start', 0))
    count = int(request.args.get('count', 10))
    
    if not filename:
        return jsonify([])
        
    data = read_data(filename, start_idx, count)
    return jsonify(data)

if __name__ == '__main__':
    event_handler = FileChangeHandler()
    observer = Observer()
    observer.schedule(event_handler, path='datas', recursive=False)
    observer.start()
    
    try:
        app.run(debug=True, port=5000, host='0.0.0.0')
    finally:
        observer.stop()
        observer.join()
